//
//  KoiJson.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 16.04.25.
//

import Foundation

struct DoubleOrString: Codable {
    var value: Double

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let doubleValue = try? container.decode(Double.self) {
            // 如果直接是 Double 类型
            self.value = doubleValue
        } else if let stringValue = try? container.decode(String.self), let doubleFromString = Double(stringValue) {
            // 如果是 String 类型并且可以转换为 Double
            self.value = doubleFromString
        } else {
            // 如果无法解析，抛出错误
            throw DecodingError.typeMismatch(
                Double.self,
                DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Expected Double or String convertible to Double")
            )
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(value)
    }
}


extension String {
    
    func jsonDecode<T : Decodable>() -> T? {
        if let jsonData = self.data(using: .utf8) {
            if let data = try? JSONDecoder().decode(T.self, from: jsonData) {
                return data
            }
        }
        return nil
    }
}


extension Encodable {
    
    func jsonEncode() -> String  {
        if let jsonData = try? JSONEncoder().encode(self) {
            let jsonStr = String(data: jsonData, encoding: .utf8)
            return jsonStr ?? ""
        }
        return ""
    }
}

extension Array where Element : Encodable {
    
    func jsonEncode() -> String {
        if let jsonData = try? JSONEncoder().encode(self) {
            let jsonStr = String(data: jsonData, encoding: .utf8)
            return jsonStr ?? ""
        }
        return ""
    }
}
